package com.huluobo.appbase.network

import android.widget.Toast
import com.huluobo.appbase.BaseApplication
import com.huluobo.appbase.R
import com.huluobo.appbase.utils.NetWorkUtil
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * Created by lc on 2023/2/28.
 * 请求工具
 */
object RetrofitServiceBuilder {
    /**
     * 初始化缓存个数
     */
    private const val INIT_SIZE = 5

    /**
     * 创建存储对象,最大个数不大于初始个数(5)
     * key:Service这个接口,请求的方法
     * value:具体请求的返回
     */
    var httpHashMap = object : LinkedHashMap<String, Any>(INIT_SIZE, 1f, true) {
        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Any>?): Boolean {
            return size > INIT_SIZE
        }
    }

    /**
     * 请求方法
     * @param clazz 传入请求的接口
     */
    fun <T> createService(clazz: Class<T>, baseApi: String = BaseApi.MAIN_API): T? {
        //网络未连接
        if (!NetWorkUtil.isConnected(BaseApplication.context)) {
            Toast.makeText(
                BaseApplication.context,
                BaseApplication.context.getString(R.string.network_disconnect), Toast.LENGTH_SHORT
            ).show()
            return null
        }

        //如果缓存中存在当前网络请求,则取出
        if (httpHashMap.containsKey(clazz.name)) {
            return httpHashMap[clazz.name] as T
        }

        //添加日志拦截器
        val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                HttpLoggingInterceptor.Logger.DEFAULT.log(message)
            }
        })
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        val builder = OkHttpClient.Builder().addInterceptor(interceptor)

        //创建retrofit
        val retrofit: Retrofit = Retrofit.Builder().baseUrl(baseApi).client(builder.build())
            .addConverterFactory(GsonConverterFactory.create()).build()

        val service = retrofit.create(clazz)
        httpHashMap[clazz.name] = service as Any

        return retrofit.create(clazz)
    }
}